package array;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

public class LongestSubstringWithoutRepeatingCharacters3 {

    @Test
    public void test() {
        lengthOfLongestSubstring("abcabcbb");
        lengthOfLongestSubstring("bbbbb");
        lengthOfLongestSubstring("pwwkew");
        lengthOfLongestSubstring("tmmzuxt");
    }

    public int lengthOfLongestSubstring(String s) {
        char[] c = s.toCharArray();
        int l = 0;
        int r = 0;
        int maxLen = 0;
        //Map<Character, Integer> map = new HashMap<>(s.length() * 3/2);
        Set<Character> set = new HashSet<>(s.length() * 3/2);
        while (r < c.length) {
            if (!set.contains(c[r])) {
                maxLen = Math.max(maxLen, r-l+1);
                set.add(c[r]);
            } else {
                while (c[l] != c[r] && l < r) {
                    // 一定要删除, 之前忘了
                    set.remove(c[l]);
                    l++;
                }
                if (l < r) {
                    l++;
                }
            }
            r++;
        }
        System.out.format("s: %s, maxLen: %d\n", s, maxLen);
        return maxLen;
    }
}
